<?php if (defined("YTDJ") or die()); 

class Entity extends YTDJClass {
	
	const TYPE_TEXT 	= 1;
	const TYPE_INT 		= 2;
	const TYPE_FLOAT 	= 3;
	const TYPE_DATETIME = 4;
	const TYPE_DATE 	= 5;
	const TYPE_TIME 	= 6;
	
	var $_db;
	
	function initDB($table, $primary) {
		$this->_db = array("table" => $table, "primary" => $primary);
		$db = &DB::getInstance();
		$db->select("DESCRIBE $table");
		$this->_db["structure"] = $db->get_obj();		
	}
	
	function initEntity($id) {
		$db = &DB::getInstance();
		$db->select("SELECT * FROM {$this->_db["table"]} WHERE {$this->_db["primary"]} = '".addslashes($id)."'");
		$attrs = $db->get_obj();
		if ($attrs[0]) {
			foreach ($attrs[0] as $key => $value) {
				$this->$key = $value;
			}
			$this->_db["found"] = true;
			return true;
		} else {
			$this->_db["found"] = false;
			return $this->insert(array($this->_db["primary"] => $id));
		}
	}
	
	function set($name, $value) {
		$this->$name = $value;
		$db = &DB::getInstance();
		return $db->update_array($this->_db["table"], array($name => $value), "{$this->_db["primary"]} = '".addslashes($this->{$this->_db["primary"]})."'");
	}
	
	function setArray($metaArray = array()) {
		$result = true;
		$this->parseMetaArray($metaArray);
		foreach($metaArray as $key => $meta) {
			$result = $result * $this->set($key, $meta);
		}
		return $result;
	}
	
	function parseMetaArray(&$meta) {
		return true;
	}
	
	function get($name) {
		return $this->$name;
	}
	
	function insert($values) {
		$db = &DB::getInstance();
		return $db->insert_array($this->_db["table"], $values);
	}
	
	function delete($id) {
		$db = &DB::getInstance();
		return $db->update_sql("DELETE FROM {$this->_db["table"]} WHERE {$this->_db["primary"]} = '".addslashes($id)."'");
	}
	
	function hasRecord() {
		return $this->_db["found"];
	}
	
	function getType($name) {
		foreach($this->_db["structure"] as $column) {
			if (strtolower($column->Field) == strtolower($name)) {
				// do something
			}
		}
	}
	
}

?>